package com.hoperun.controller.admin;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.hoperun.bean.AdminManager;
import com.hoperun.bean.AdminPermissions;
import com.hoperun.bean.AdminRoles;
import com.hoperun.controller.common.BaseController;
import com.hoperun.framework.ex.XHZException;
import com.hoperun.framework.ibatis.page.BootGrid;
import com.hoperun.framework.ibatis.page.BootGridPage;
import com.hoperun.framework.models.DataView;
import com.hoperun.framework.query.Criteria;
import com.hoperun.framework.util.Constant;
import com.hoperun.framework.util.DateUtils;
import com.hoperun.service.IAdminManagerSV;
import com.hoperun.service.IAdminRolesSV;
import com.hoperun.utils.ErrorCode;
import com.hoperun.utils.Constant.RecordState;

/**
 * Copyright: Copyright (c) 2016 GUO~AN <br/>
 * ClassName: AdminRolesController.java
 * 
 * @Description:
 * 
 * @version: v1.0.0
 * @author: fuyu
 * @date: 2016-1-8 上午9:11:06
 * 
 *        Modification History: Date Author Version Description
 *        ---------------------------------------------------------* 2016-1-8
 *        fuyu v1.0.0 修改理由
 */
@Controller
@RequestMapping("/admin/admin/roles")
@RequiresUser
public class AdminRolesController extends BaseController {

	@Resource
	private IAdminRolesSV adminRolesSV;
	@Resource
	private IAdminManagerSV adminManagerSV;

	@ModelAttribute
	public void populateModel(final HttpServletRequest request,
			ModelMap modelMap) {
		try {
			super.initMenus(request, modelMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/{menu}/{menuNext}")
	public String index(@PathVariable long menu, @PathVariable long menuNext,
			ModelMap modelMap) {

		modelMap.put("menuType", menu);
		modelMap.put("menuNextType", menuNext);

		return "admin:adminroles.list";
	}

	@RequestMapping("/page")
	@ResponseBody
	public BootGridPage<AdminRoles> identityUserPage(BootGrid<AdminRoles> grid,
			AdminRoles adminRoles, ModelMap modelMap) {
		BootGridPage<AdminRoles> pageModel = new BootGridPage<AdminRoles>();

		try {
			Criteria criteria = new Criteria();

			if (null == grid)
				return new BootGridPage<AdminRoles>();

			String roleName = grid.getSearchPhrase();
			if (StringUtils.isNotBlank(roleName)) {
				criteria.addLike(AdminRoles.COL_ROLE_NAME,
						"%" + roleName + "%", Criteria.AND);
			}
			criteria.addEqual(AdminRoles.COL_STATUS, RecordState.STS_USE,
					Criteria.AND);
			pageModel = adminRolesSV.queryPage(criteria, grid);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return pageModel;
	}

	@RequestMapping("/create")
	public String create(ModelMap modelMap) {
		modelMap.addAttribute("method", "save");
		modelMap.addAttribute("row", new AdminRoles());
		return "adminAlone:adminroles.info";
	}

	@RequestMapping("/modify/{id}")
	public String modify(@PathVariable Long id, ModelMap modelMap,
			final HttpServletRequest request) {
		AdminRoles adminRoles = null;
		try {
			adminRoles = adminRolesSV.queryById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelMap.addAttribute("method", "update");
		modelMap.addAttribute("row", adminRoles);
		return "adminAlone:adminroles.info";
	}

	@RequestMapping("/detail/{id}")
	public String detail(@PathVariable Long id, ModelMap modelMap,
			final HttpServletRequest request) {
		AdminRoles adminRoles = null;
		try {
			adminRoles = adminRolesSV.queryById(id);

			adminRoles.setCreateStrTime(DateUtils.dateString(adminRoles
					.getCreatime()));
			if (null != adminRoles.getUpdatetime()) {
				adminRoles.setUpdateStrTime(DateUtils.dateString(adminRoles
						.getUpdatetime()));
			}
			AdminManager am = adminManagerSV.queryById(adminRoles.getCreator());
			adminRoles.setStrCreator(am.getRealName());
			if (StringUtils.isNotBlank("" + adminRoles.getUpdator())) {
				am = adminManagerSV.queryById(adminRoles.getUpdator());
				adminRoles.setStrUpdator(am.getRealName());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelMap.addAttribute("row", adminRoles);
		return "adminAlone:adminroles.detail";
	}

	@RequestMapping("/save")
	@ResponseBody
	public DataView save(AdminRoles adminRoles) {
		DataView dataView = new DataView();

		try {
			adminRolesSV.save(adminRoles);

			dataView.setCode(Constant.SUCCESS);
			dataView.setMessage("新增成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dataView;
	}

	@RequestMapping("/update")
	@ResponseBody
	public DataView update(AdminRoles adminRoles) {
		DataView dataView = new DataView();

		if (null == adminRoles
				|| StringUtils.isBlank("" + adminRoles.getRoleId())) {
			throw new XHZException(ErrorCode.MISS_PARAM, null,
					new Object[] { "id信息" });
		}

		try {
			adminRolesSV.update(adminRoles);

			dataView.setCode(Constant.SUCCESS);
			dataView.setMessage("修改成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dataView;
	}

	@RequestMapping("/find/{id}")
	@ResponseBody
	public AdminRoles findOne(@PathVariable Long id) {
		AdminRoles adminRoles = null;
		try {
			adminRoles = adminRolesSV.queryById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return adminRoles;
	}

	@RequestMapping("/toAlloc/{ids}")
	public String toAlloc(@PathVariable Long[] ids, ModelMap modelMap,
			final HttpServletRequest request) {
		List<AdminPermissions> currentList = new ArrayList<AdminPermissions>();
		try {
			if (Constant.ONE == ids.length) {
				currentList = adminRolesSV.queryPermissByRoleId(ids[0]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelMap.addAttribute("ids", ids);
		modelMap.addAttribute("currentList",
				JSONObject.toJSONString(currentList));
		return "adminAlone:adminroles.alloc";
	}

	@RequestMapping("/alloc")
	@ResponseBody
	public DataView alloc(
			@RequestParam(value = "permId", defaultValue = "0") Long permId) {
		DataView dataView = new DataView();
		List<AdminPermissions> list = new ArrayList<AdminPermissions>();
		try {
			list = adminRolesSV.queryPermissByMgrId();// 当前用户所有权限
			if (CollectionUtils.isNotEmpty(list)) {
				dataView.setCode(Constant.SUCCESS);
				dataView.setData(list);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dataView;
	}

	@RequestMapping("/alloc/save")
	@ResponseBody
	public DataView allocSave(String permission, Long[] roleIds) {
		DataView dataView = new DataView();
		try {
			if (ArrayUtils.isEmpty(roleIds)) {
				throw new XHZException(ErrorCode.ILLEGAL_PARAM, null,
						new Object[] { "roleId" });
			}
			adminRolesSV.allocSave(permission, roleIds);
			dataView.setCode(Constant.SUCCESS);
			dataView.setMessage("操作成功");
		} catch (Exception e) {
			dataView.setMessage("操作失败");
			e.printStackTrace();
		}

		return dataView;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public DataView delete(Long[] ids) {
		DataView dataView = new DataView();
		AdminRoles adminRoles = null;
		try {
			if (ArrayUtils.isEmpty(ids)) {
				throw new XHZException(ErrorCode.ILLEGAL_PARAM, null,
						new Object[] { "id" });
			}
			for (Long id : ids) {
				adminRoles = new AdminRoles();
				adminRoles.setRoleId(id);
				adminRoles.setStatus(RecordState.STS_DEL);
				adminRolesSV.update(adminRoles);

			}
			dataView.setCode(Constant.SUCCESS);
			dataView.setMessage("操作成功");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return dataView;
	}
}
